// formPackage/pages/enterApply/fullNameApply/fullNameApply.js
import { chooseAndUploadQiniuActicon } from "../../../../service/upload_service"
import { loginWxAction, sendApplyAgentCodeAction } from "../../../../service/config"
import { queryUserPayInfo, bindUserRelation } from "../../../../service/user_service"
import { createAgentEnter, queryAgentEnterDetail, updateAgentEnterInfo } from "../../../../service/enter_service"
import { expertCloseRequest } from '../../../../service/expert_service'
import debounce from "../../../../tools/debounce"
import {
  CHECK_SUCCESS,
  CHECK_FAIL,
  CHECK_PROGRESS
} from "../../../../service/base_service"

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    checkSuccess: CHECK_SUCCESS,
    checkFail: CHECK_FAIL,
    checkProgress: CHECK_PROGRESS,
    bottomTitle: "下一步",
    showSuccessPop: false,
    formData: {
      code: "",
      data: {},
      payInfo: {},
    },
    protocolUrl: "https://protocol.ylyc.top/yjy_user_protocol.html",
    isFoldBankInfo: false,//是否展开银行卡信息
    infoData: {
      "areaName": "",
      "areaCode": "",
      "cityName": "",
      "cityCode": "",
      "provinceName": "",
      "provinceCode": "",
      "companyName": "",
      "contactName": "",
      "mainBusinessRange": "",
      "phone": "",
      "weChat": "",
      "position": "",
      "proveImg": "",//身份证明
      "recommendWxUserId": "",//推荐人id
      "isOpenView": true,//是否首页展示
    },
    payInfoData: {
      "bankAccount": "",
      "bankName": "",
      "cardBack": "",
      "cardFront": "",
      "openBank": "",
      "openName": "",
    },
    showCityArea: false,//所在区域
    singlePopType: "",//单项弹窗类型
    singlePopTitle: "选择",//单项弹窗标题
    showSinglePop: false,//弹出单项弹窗
    isProtocol: false,
    couponCodeBtnStatus: false,
    couponCodeBtnTitle: "获取验证码",
    snsMsgWait: 60,//倒计时
    isEdit: true,
    examineStatus: 0,//1:审核中，2:审核通过，3:审核失败
    disabled: false,
    isEditPayInfo: true,//是否可编辑这个支付信息
    isScanEnter: false,
    isShare: false,//是否分享进来的
    bindUserId: "",//挂级关系id
    isCheckOpen: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isCheckOpen: app.globalData.isCheckOpen
    })
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      console.log("JJLog:9999999===:" + scene);
      let sceneArray = scene.split("&");
      let firstArr = sceneArray[0].split("=");
      let secondArr = sceneArray[1].split("=");

      let b = secondArr[1];
      let userId = firstArr[1];
      if (b == 1) {
        this.setData({
          isScanEnter: true
        })
      }
      this.setData({
        isShare: true,
        'infoData.recommendWxUserId': userId,
        bindUserId: userId
      })

      this.userWxLogin();

      return;
    }

    if (options.isShare) {
      this.setData({
        isShare: true,
        'infoData.recommendWxUserId': options.userId,
        bindUserId: options.userId
      })
      this.userWxLogin();
      return;
    }

    this.queryAgentEnterDetail();




  },
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.name = data.name || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.id;
        app.globalData.qrCode = data.qrCode || "";
        app.globalData.isAuthUserInfo = data.isAuthUserInfo;
        app.globalData.weChat = data.weChat || "";
        app.globalData.roleName = data.roleName || "";
        app.globalData.companyName = data.companyName || "";
        app.globalData.companyNumber = data.companyNumber || "";
        app.globalData.openId = data.openId;
        //绑定挂级关系:
        if (this.data.bindUserId) {
          this.bindUserRelation();
        }
        this.queryAgentEnterDetail();
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
    })
  },
  //绑定挂级关系:
  bindUserRelation() {
    let type = 1;
    if (this.data.isScanEnter) {
      type = 1;
    } else {
      type = 2;
    }
    bindUserRelation(type, this.data.bindUserId).then(res => {
      console.log("JJLog:绑定挂级关系:" + JSON.stringify(res));
      if (res.code == 200) {

      }
    }).catch(err => {
      console.error("JJLog:bindUserRelation:", err);
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    // console.log("JJLog:选择的银行是:" + app.globalData.selectBankName);
    if (app.globalData.selectBankName) {
      // console.log("JJLog:再看看:" + app.globalData.selectBankName);
      this.setData({
        'payInfoData.bankName': app.globalData.selectBankName
      })
      app.globalData.selectBankName = null;
    }
  },
  upOrDownClick() {

    wx.showLoading();
    expertCloseRequest().then(res => {
      wx.hideLoading();
      console.log("JJLog:关闭首页显示请求:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          'infoData.isOpenView': !this.data.infoData.isOpenView
        })
      }

    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:关闭首页显示报错:" + JSON.stringify(err));
    })

  },

  //查询已有的经纪人入驻信息:
  queryAgentEnterDetail() {
    wx.showLoading();
    queryAgentEnterDetail().then(res => {
      wx.hideLoading();
      console.log("JJLog:回填数据是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data.data) {
          this.setData({
            'formData.data': res.data.data,
            'formData.payInfo': res.data.payInfo,
            examineStatus: res.data.data.examineStatus || 0,
            isEdit: res.data.data.isEdit,
            payInfoData: res.data.payInfo,
            infoData: res.data.data,
          })
          if (this.data.bindUserId) {
            this.setData({
              'infoData.recommendWxUserId': this.data.bindUserId
            })
          }
        }
        if (res.data.data && res.data.data.contactName && this.data.examineStatus != 0) {
          this.setData({
            bottomTitle: "更新申请"
          })
        }
        if (this.data.examineStatus == 1) {
          this.setData({
            disabled: true
          })
        }

        this.setData({
          payInfoData: app.globalData.userPayInfo,
          isEditPayInfo: app.globalData.userPayInfo.isEdit
        })
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:回填数据报错:" + JSON.stringify(err));
    })
  },



  //单项输入回调:
  inputCellChange(e) {
    let type = e.detail.key;
    let changeValue = `infoData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },
  //手机号输入绑定:
  bindPhoneInputValue(e) {
    this.setData({
      'infoData.phone': e.detail.value
    })
  },
  //验证码:
  inputCodeChange(e) {
    this.setData({
      'formData.code': e.detail.value
    })
  },
  inputPayChange(e) {
    let type = e.detail.key;
    let changeValue = `payInfoData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },
  //单项选择弹出弹窗:
  singleSelectPop(e) {
    if (this.data.examineStatus == 1) {
      return;
    }
    let type = e.currentTarget.dataset.type;
    if (type == "area") {
      //选择区域
      this.setData({
        showCityArea: true
      })
    } else if (type == "bankName") {
      if (!this.data.isEditPayInfo) {
        return;
      }
      wx.navigateTo({
        url: '/formPackage/pages/selectBankPage/selectBankPage',
      })
    }
    else if (type == "mainType") {
      //主推类型 
      this.setData({
        showSinglePop: true,
        singlePopType: type,
        singlePopTitle: "主推类型"
      })
    } else if (type == "position") {
      this.setData({
        showSinglePop: true,
        singlePopType: "newRole",
        singlePopTitle: "选择职位"
      })
    }
  },
  //城市区域回调;
  cityPopConfirm(e) {
    let result = e.detail.result;//区县一层的
    this.setData({
      'infoData.areaName': result[2].name,
      'infoData.areaCode': result[2].code,
      'infoData.cityName': result[1].name,
      'infoData.cityCode': result[1].code,
      'infoData.provinceName': result[0].name,
      'infoData.provinceCode': result[0].code,
      showCityArea: false,
    })
  },
  //单项选择回调:
  singlePopSelectCallback(e) {
    let result = e.detail.result;
    let type = e.detail.type;

    if (type == "bankName") {
      this.setData({
        'payInfoData.bankName': result.value,
      })
    }
    if (type == "newRole") {
      this.setData({
        'infoData.position': result.label,
      })
    }

    this.setData({
      showSinglePop: false
    })
  },
  singlePopHide() {
    this.setData({
      showSinglePop: false
    })
  },
  cityPopHidden() {
    this.setData({
      showCityArea: false
    })
  },
  // 上传图片
  pushImgAction(e) {
    if (this.data.examineStatus == 1) {
      return;
    }

    let type = e.detail.type;
    chooseAndUploadQiniuActicon('id').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      if (type == "idFront") {
        this.setData({
          'payInfoData.cardFront': res.complateUrl
        })
      } else if (type == "idBack") {
        this.setData({
          'payInfoData.cardBack': res.complateUrl
        })
      }

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },

  //上传单独那一张身份证明:
  pushProverImgAction() {
    chooseAndUploadQiniuActicon('prove').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      this.setData({
        'infoData.proveImg': res.complateUrl
      })

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },
  // 上传微信二维码
  pushWechatImgAction() {
    chooseAndUploadQiniuActicon('wechat').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      this.setData({
        'infoData.ewmPic': res.complateUrl
      })

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },


  /** 发送验证码 */
  clickSendCode() {
    if (this.data.couponCodeBtnStatus) {
      return;
    }
    let that = this;
    //点击了发送按钮，就先禁用掉这个按钮点击
    this.setData({
      couponCodeBtnStatus: true,
    })
    //调用发送验证码接口:
    let phone = this.data.infoData.phone;
    let warn = null;
    if (phone == '') {
      warn = "号码不能为空";
    } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
      warn = "手机号格式不正确";
    } else {
      sendApplyAgentCodeAction(phone).then((data) => {
        //当手机号正确的时候提示用户短信验证码已经发送
        wx.showToast({
          title: '短信验证码已发送',
          icon: 'none',
          duration: 2000
        });
        let inter = setInterval(function () {
          this.setData({
            couponCodeBtnStatus: true,
            couponCodeBtnTitle: this.data.snsMsgWait + 's后重发',
            snsMsgWait: this.data.snsMsgWait - 1
          });
          if (this.data.snsMsgWait < 0) {
            clearInterval(inter)
            this.setData({
              couponCodeBtnTitle: '重新发送',
              snsMsgWait: 60,
              couponCodeBtnStatus: false
            });
          }
        }.bind(this), 1000);

      }).
        catch((err) => {
          that.setData({
            couponCodeBtnStatus: false
          })
          wx.showToast({
            icon: 'none',
            title: err,
          })
        })


    }
    if (warn != null) {
      wx.showModal({
        title: '提示',
        content: warn
      })
      that.setData({
        couponCodeBtnStatus: false
      })
      return;
    }

  },

  submitInfoAction() {
    let payInfoData = this.data.payInfoData;
    let qmData = this.data.infoData;


    if (!qmData.contactName) {
      wx.showToast({
        title: '请输入申请人',
        icon: "none"
      })
      return;
    }
    if (!qmData.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: "none"
      })
      return;
    }
    if (!this.data.formData.code) {
      wx.showToast({
        title: '请输入验证码',
        icon: "none"
      })
      return;
    }
    // if (!qmData.weChat) {
    //   wx.showToast({
    //     title: '请输入微信号',
    //     icon: "none"
    //   })
    //   return;
    // }
    if (!qmData.areaName) {
      wx.showToast({
        title: '请选择所在区域',
        icon: "none"
      })
      return;
    }
    if (!qmData.proveImg) {
      wx.showToast({
        title: '请上传身份证明图片',
        icon: "none"
      })
      return;
    }
    // if (!qmData.mainBusinessRange) {
    //   wx.showToast({
    //     title: '请输入主推类型',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.bankName) {
    //   wx.showToast({
    //     title: '请选择银行',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.bankAccount) {
    //   wx.showToast({
    //     title: '请输入银行卡号',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.openName) {
    //   wx.showToast({
    //     title: '请输入开户名',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.cardFront) {
    //   wx.showToast({
    //     title: '请上传身份证正面照',
    //     icon: "none"
    //   })
    //   return;
    // }
    // if (!payInfoData.cardBack) {
    //   wx.showToast({
    //     title: '请上传身份证反面照',
    //     icon: "none"
    //   })
    //   return;
    // }
    if (!this.data.isProtocol) {
      wx.showToast({
        title: '请同意用户政策与隐私协议',
        icon: "none"
      })
      return;
    }

    this.setData({
      'formData.data': qmData,
      'formData.payInfo': payInfoData
    })

    if (this.data.examineStatus != 0) {
      debounce(this.updateApplyData);
    } else {
      debounce(this.submitInfoRequest);
    }

  },
  //提交申请数据:
  submitInfoRequest() {
    wx.showLoading();
    console.log("JJLog:提交资料是:" + JSON.stringify(this.data.formData));
    createAgentEnter(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          showSuccessPop: true
        })
        // console.log("JJLog:资料提交成功:" + JSON.stringify(res));
        // wx.navigateTo({
        //   url: '/formPackage/pages/platformModule/platformPayPage/platformPayPage?type=' + "agent" + "&id=" + res.data.id,
        // })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon: "none"
      })
    })
  },
  //更新申请数据;
  updateApplyData() {
    wx.showLoading();
    console.log("JJLog:提交资料是:" + JSON.stringify(this.data.formData));
    updateAgentEnterInfo(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        //待支付
        if (this.data.examineStatus == 4) {
          wx.navigateTo({
            url: '/formPackage/pages/platformModule/platformPayPage/platformPayPage?type=' + "agent" + "&id=" + this.data.formData.data.id,
          })
          return;
        }
        this.setData({
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon: "none"
      })
    })
  },


  //同意协议
  agreeProtocolAction() {
    this.setData({
      isProtocol: !this.data.isProtocol
    })
  },
  //前往协议页面
  pushToProtocol() {
    app.globalData.webUrl = this.data.protocolUrl
    wx.navigateTo({
      url: '/pages/webViewPage/webViewPage',
    })
  },

  //展开银行卡信息
  foldBankInfoAction() {
    this.setData({
      isFoldBankInfo: this.data.isFoldBankInfo ? false : true
    })
  },

  successPopSure() {
    this.setData({
      showSuccessPop: false,
    })
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },


  onShareAppMessage: function () {
    let userId = app.globalData.userId || ""
    let nickName = app.globalData.name || app.globalData.nickName;
    let imgPath = "https://saas.img.ylyc.top/bg/enteragentmiddlebg_icon.png";
    let path = "/formPackage/pages/enterApply/agentApply/agentApply?isShare=1" + "&userId=" + userId
    return {
      title: nickName + "邀请您入驻万众卖房",
      path: path,
      imageUrl: imgPath,
    }
  }

})